<?php
/**
* @file $Id: index.php 458 2007-04-23 05:49:36Z focus-sis $
* @package Focus/SIS
* @copyright Copyright (C) 2006 Andrew Schmadeke. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.txt
* Focus/SIS is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.txt for copyright notices and details.
*/

error_reporting(1);
if (!function_exists('pg_connect')) {
	echo "
	Your version of PHP does not include PostgreSQL support.  
	<ul>
		<li>If you've install Focus/SIS on a Mac OS X machine, 
			download and install the PHP and PostgreSQL packages 
			from Marc Liyanage's 
			<a href='http://www.entropy.ch'>
				Entropy.ch
			</a> site.
		</li>
		<li>If using Windows, open the php.ini file in a text 
			editor like WordPad and remove the semi-colon before 
			the line \";pg_sql.dll\"
		</li>
		<li> If you're using a Linux or Unix server, 
			you'll probably need to recompile PHP using the 
			--with-pgsql option.
		</li>
	</ul>";
}

require_once('Warehouse.php');
$db_date = DBDate();

if ($_REQUEST['modfunc'] == 'logout') {
	if ($_SESSION['USERNAME'] 
	||  $_SESSION['STUDENT_ID']
	){
		session_destroy();
		header("Location: $_SERVER[PHP_SELF]?modfunc=logout"
				. (($_REQUEST['reason'])
					? '&reason='.$_REQUEST['reason']
					: ''
				));
		exit;
	}
}

if ($_REQUEST['USERNAME'] 
&&  $_REQUEST['PASSWORD']
){
	if (SystemPreferences('AUTHENTICATION') == 'ldap') {
		$auth_cnx = ldap_connect($AuthLDAPHost);
		$r = ldap_bind($auth_cnx);
		$search_result = ldap_search( $ds
									, $AuthLDAPBaseDN
									, "uid=$_REQUEST[USERNAME]"
									);
		
		$info = ldap_get_entries($auth_cnx, $search_result);
		for ($i = 0; $i < $info["count"]; $i++) {
			$theuserpassword = $info[$i]["userpassword"][0];
			$thedescription  = $info[$i]["description"][0];
			$descexploded    = explode(", ", $thedescription);
			$theDN = $info[$i]["dn"];
		}

		$LOGINSUCCESSFUL = ldap_bind($auth_cnx, $theDN, $_REQUEST['PASSWORD']);

		if ($LOGINSUCCESSFUL) {
			$_REQUEST['USERNAME'] = DBEscapeString($_REQUEST['USERNAME']);
			$login_RET = DBGetRow("
					SELECT        USERNAME
					 ,            PROFILE 
					FROM          USERS 
				    WHERE         SYEAR = '$DefaultSyear' 
					 AND          UPPER(USERNAME) = UPPER('$_REQUEST[USERNAME]')
					");
					
			$student_RET = DBGetRow("
					SELECT        USERNAME
					 ,            STUDENT_ID 
					FROM          STUDENTS 
					WHERE         UPPER(USERNAME) = UPPER('$_REQUEST[USERNAME]')
					");
		}

		if (strtoupper($login_RET['USERNAME']) == strtoupper($_REQUEST['USERNAME']) 
		&&  $login_RET['PROFILE'] != 'none'
		){
			$_SESSION['USERNAME'] = $login_RET['USERNAME'];
		}
	}
	else {
		$_REQUEST['USERNAME'] = DBEscapeString($_REQUEST['USERNAME']);
		$_REQUEST['PASSWORD'] = DBEscapeString($_REQUEST['PASSWORD']);

		$login_RET = DBGetRow("
				SELECT        USERNAME
				 ,            PROFILE
				 ,            STAFF_ID
				 ,            to_char(LAST_LOGIN,'FMDay, HH12:MI AM') AS LAST_LOGIN
				 ,            FAILED_LOGIN 
				FROM          USERS 
				WHERE         SYEAR = '$DefaultSyear' 
				 AND          UPPER(USERNAME) = UPPER('$_REQUEST[USERNAME]') 
				 AND          UPPER(PASSWORD) = UPPER('$_REQUEST[PASSWORD]')
				");
				
		$student_RET = DBGetRow("
				SELECT        s.USERNAME
				 ,            s.STUDENT_ID
				 ,            to_char(s.LAST_LOGIN,'FMDay, HH12:MI AM') AS LAST_LOGIN
				 ,            s.FAILED_LOGIN 
				FROM          STUDENTS s
				 ,            STUDENT_ENROLLMENT se 
				WHERE         UPPER(s.USERNAME) = UPPER('$_REQUEST[USERNAME]')
				 AND          UPPER(s.PASSWORD) = UPPER('$_REQUEST[PASSWORD]') 
				 AND          se.STUDENT_ID = s.STUDENT_ID 
				 AND          se.SYEAR = '$DefaultSyear'
				 AND          CURRENT_DATE >= se.START_DATE
				 AND     (    CURRENT_DATE <= se.END_DATE 
				  OR          se.END_DATE IS NULL   )
				");

		if (!$login_RET 
		&&  !$student_RET 
		&&  $FocusAdmins
		){
			$admin_RET = DBGetRow("
					SELECT        STAFF_ID 
					FROM          USERS 
					WHERE         PROFILE = 'admin' 
					 AND          SYEAR = '$DefaultSyear' 
					 AND          STAFF_ID IN ($FocusAdmins) 
					 AND          UPPER(PASSWORD) = UPPER('$_REQUEST[PASSWORD]')
					");
			
			if ($admin_RET) {
				$login_RET = DBGetRow("
						SELECT        USERNAME
						 ,            PROFILE
						 ,            STAFF_ID
						 ,            LAST_LOGIN
						 ,            FAILED_LOGIN 
						FROM          USERS 
						WHERE         SYEAR = '$DefaultSyear' 
						AND           UPPER(USERNAME) = UPPER('$_REQUEST[USERNAME]')
						");
				
				$student_RET = DBGetRow("
						SELECT        s.USERNAME
						 ,            s.STUDENT_ID
						 ,            s.LAST_LOGIN
						 ,            s.FAILED_LOGIN 
						FROM          STUDENTS s
						 ,            STUDENT_ENROLLMENT se 
						WHERE         UPPER(s.USERNAME) = UPPER('$_REQUEST[USERNAME]') 
						 AND          se.STUDENT_ID = s.STUDENT_ID 
						 AND          se.SYEAR = $DefaultSyear 
						 AND          $db_date >= se.START_DATE 
						 AND   (      $db_date <= se.END_DATE 
						  OR          se.END_DATE IS NULL   )
						");
			}
		}
		
		if ($login_RET 
		&&  $login_RET['PROFILE'] != 'none'
		){
			$_SESSION['USERNAME']   = $login_RET['USERNAME'];
			$_SESSION['STAFF_ID']   = $login_RET['STAFF_ID'];
			$_SESSION['LAST_LOGIN'] = $login_RET['LAST_LOGIN'];
			$failed_login           = $login_RET['FAILED_LOGIN'];
			
			if ($admin_RET) {
				DBUpdate('USERS'
				/*WHERE*/	, array( 'STAFF_ID' => $login_RET['STAFF_ID'] )
				/*SET*/	, array( 'LAST_LOGIN' => $db_date )
						);
			}
			else {
				DBUpdate('USERS'
				/*WHERE*/	, array( 'STAFF_ID' => $login_RET['STAFF_ID'] )
				/*SET*/	, array( 'LAST_LOGIN' => $db_date
							   , 'FAILED_LOGIN' => '# NULL' )
						);
			}
			$LOGINSUCCESSFUL = 1;
		}
	}

	if (!$LOGINSUCCESSFUL 
	&&  $login_RET['PROFILE'] == 'none'
	){
		$error[] = _("Your account has not yet been activated.  When your account has been verified by school administration, you will be notified by email.");
	}
	elseif (strtoupper($student_RET['USERNAME']) == strtoupper($_REQUEST['USERNAME'])) {
		$_SESSION['STUDENT_ID'] = $student_RET['STUDENT_ID'];
		$_SESSION['USERNAME']   = $student_RET['USERNAME'];
		$_SESSION['LAST_LOGIN'] = $student_RET['LAST_LOGIN'];

		DBUpdate('STUDENTS'
				, array( 'STUDENT_ID' => $student_RET['STUDENT_ID'] )
				, array( 'LAST_LOGIN' => 'CURRENT_TIMESTAMP' )
				);
	}
	else {
		$error[] = _("Incorrect username or password.<br />Please try logging In again.");
	}
}

if ($_REQUEST['modfunc'] == 'create_account') {
	Warehouse('header');
	$_FOCUS['allow_edit'] = true;
	
	if ($_REQUEST['staff']['USERNAME']) {
		$_REQUEST['modfunc'] = 'update';
	}
	else {
		$_REQUEST['staff_id'] = 'new';
	}
	
	include('modules/Users/User.php');
	
	if (!$_REQUEST['staff']['USERNAME']) {
		Warehouse('footer_plain');
	}
	else {
		$note[] = _('Your account has been created.  You will be notified by email when it is verified by school administration and you can log in.');
		session_destroy();
	}
}

if (!$_SESSION['USERNAME'] 
&&  !$_SESSION['STUDENT_ID'] 
&&  $_REQUEST['modfunc'] != 'create_account'
){
	Warehouse('header');
	
	echo "
<body	onLoad='document.loginform.USERNAME.focus()
	<div style='font-size: .6em;'>
	<div	style='margin: 3em;
					width: 65.25em;
					height: 45em;'>
		<img	src='./assets/login-bg-image.png' 
				style='width:65.25em; 
						height:45em;' />
	</div>";


	if ($_REQUEST['reason']) {
		$note[] = _('You must have javascript enabled to use Focus/SIS.');
	}
	
	echo "
	<form	name='loginform'
			method='post'
			action='index.php'
			style='font-family: Arial, Helvetica, sans-serif;
					position: absolute;
					top: 19.5em;
					left: 34.5em;
					color: gray;
					white-space: nowrap;
					margin: 0;
					padding: 0;
					line-height: 1.5em;'>
		<span style='font-size: 1.2em;'>
			" . _('Username') . ":&nbsp;
			<input	type='text'
					name='USERNAME'
					maxlength='25'
					style='font-family: Arial, Helvetica, sans-serif;
							font-size: .9em;
							width:13em;
							margin:0;'/>
			<br/>
			<br/>
			" . _('Password') . ":&nbsp;&nbsp;
			<input	type='password'
					name='PASSWORD'
					maxlength='25' 
					style='font-family: Arial, Helvetica, sans-serif;
							font-size: .9em;
							width:10em;
							margin:0;'/>
			&nbsp;				
			<input	type='submit'
					value='" . _('Login') . "' 
					style='font-family: Arial, Helvetica, sans-serif;
							font-size: 1em;
							margin:0;'/>
		</span>";
	
	
	if ($ShowCreateAccount) {
		echo "
			<br/>
			<font	size='-1'>	[
				<a	href='index.php?modfunc=create_account'>
					Create Account
				</a>	]
			</font>";
	}
	
	
	echo "
	</form>
	<p		id='disclaimer'
			style='position: absolute;
					top: 36.5em;
					width: 59.5em;
					left: 6em;
					text-align: left;
					font-family: Arial, Helvetica, sans-serif;
					margin: .75em'>
		<span	id='disclaimer'
				style='text-align: center;
						font-size: 1.3em;'>
This is a restricted network. Use of this network, its equipment, and resources
is monitored at all times and requires explicit permission from the network
administrator and Sugar Salem Student Information System. If you do not have this
permission in writing, you are violating the regulations of this network
and can and will be prosecuted to the full extent of the law. By continuing
into this system, you are acknowledging that you are aware of and agree
to these terms.
		</span>
	</p>
	<p		id='disclaimer'
			style='position: absolute;
					top: 49em;
					left: 7em;
					text-align: left;
					font-family: Arial, Helvetica, sans-serif;
					margin: .75em'>
		<span	id='disclaimer'
				style='text-align: center;
						font-size: 1.7em;'>
			<a href='http://www.focus-sis.org'>
				Focus/SIS
			</a> 
			version $FocusVersion &copy; 
			2004-" . date('Y') . "
		</span>
	</p>
	</div>
</body>";
		
	Warehouse("footer");
}
elseif ($_REQUEST['modfunc'] != 'create_account') {
	$_FOCUS = array();
	if (Preferences('MENU') != 'Top' 
	&&  User('PROFILE') != 'student'
	){
		echo "
<html>
<head><title>" . Config('TITLE') . "</title></head>
<noscript>
<meta http-equiv='REFRESH' 
		content='0;url=index.php?modfunc=logout&reason=javascript' 
/>
</noscript>
<frameset id='mainframeset' 
		rows='*,30' 
		border='0' 
		framespacing='0'
>
	<frameset cols='180,*' border=0>
		<frame name='side' 
				src='Side.php' 
				frameborder='0' 
		/>
		<frame name='body' 
				src='Modules.php?modname=misc/Portal.php' 
				frameborder='0' 
				style='border: inset #C9C9C9 2px' 
		/>
	</frameset>
	<frame name='help' src='Bottom.php' />
</frameset>
</html>";
	}
	else {
		echo "
<html>
<head><title>" . Config('TITLE') . "</title></head>
<noscript>
<meta http-equiv='REFRESH' 
		content='0;url=index.php?modfunc=logout&reason=javascript' 
/>
</noscript>
<frameset id='mainframeset' 
		rows='*,30' 
		border='0' 
		framespacing='0'
>
	<frame name='body' 
			src='Modules.php?modname=misc/Portal.php' 
			frameborder='0' 
	/>
	<frame name='help' 
			src='Bottom.php' 
	/>
</frameset>
</html>";
	}
}
?>